package com.bizmda.bizsip.config;

import cn.hutool.core.io.resource.ClassPathResource;
import com.bizmda.bizsip.common.BizException;
import com.bizmda.bizsip.common.BizResultEnum;
import lombok.Getter;
import org.yaml.snakeyaml.Yaml;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 史正烨
 */
@Getter
public class SinkConfigMapping {
    private String configPath;
    private Map<String, AbstractSinkConfig> sinkConfigMap;

    public SinkConfigMapping(String configPath) throws BizException {
        this.configPath = configPath;
        this.load();
    }

    public void load() throws BizException {
        Yaml yaml = new Yaml();
        List<Map<String,Object>> sinkMapList = null;
        try {
            if (this.configPath == null) {
                ClassPathResource resource = new ClassPathResource("/sink.yml");
                sinkMapList = (List<Map<String,Object>>)yaml.load(new FileInputStream(resource.getFile()));
            }
            else {
                sinkMapList = (List<Map<String, Object>>) yaml.load(new FileInputStream(new File(this.configPath + "/sink.yml")));
            }
        } catch (FileNotFoundException e) {
            throw new BizException(BizResultEnum.SINK_FILE_NOTFOUND,"sink.yml");
        }
        AbstractSinkConfig sinkConfig = null;
        this.sinkConfigMap = new HashMap<>(16);
        for (Map<String,Object> sinkMap:sinkMapList) {
            String type = (String)sinkMap.get("type");
            if ("rest".equalsIgnoreCase(type)) {
                sinkConfig = new RestSinkConfig(sinkMap);
            }
            else if ("rabbitmq".equalsIgnoreCase(type)) {
                sinkConfig = new RabbitmqSinkConfig(sinkMap);
            }
            else {
                continue;
            }
            this.sinkConfigMap.put(sinkConfig.getId(),sinkConfig);
        }
    }

    public AbstractSinkConfig getSinkConfig(String id) {
        return this.sinkConfigMap.get(id);
    }
}
